/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 5/22/18
Time: 6:55 AM
 */

package Cn.Sarkar.PermissionManager


import Cn.Sarkar.PermissionManager.Entities.IPermissionItem
import Cn.Sarkar.PermissionManager.Entities.IUser
import io.ktor.application.ApplicationCall
import io.ktor.auth.DigestCredential
import io.ktor.auth.HttpAuthHeader
import io.ktor.auth.UnauthorizedResponse
import io.ktor.auth.digestAuthenticationCredentials
import io.ktor.pipeline.PipelineContext
import io.ktor.response.respond

suspend fun <TSubject : Any, TContext : ApplicationCall> PipelineContext<TSubject, TContext>.fullAuthenticate(permissionManager: PermissionManager, allowedPermissions: Array<IPermissionItem>, user: IUser, action: () -> Unit) {

    val credential = context.digestAuthenticationCredentials()
            ?: DigestCredential("", "", "", "", "", "", "", "", "", "")

    val exists = permissionManager.existsNonce(credential.nonce)
    if (exists) {
        var allow = false
        allowedPermissions.forEach { item ->
            user.permissions.singleOrNull { it.code == item.code }.run {
                if (this != null) {
                    allow = true
                    return@forEach
                }
            }
        }
        if (allow) {
            action()
        }

    }
    context.respond(UnauthorizedResponse(HttpAuthHeader.digestAuthChallenge("yeganaaa")))
}

fun <ITEM : IPermissionItem> IPermissionDefs.define(item: ITEM, config: ITEM.() -> Unit): ITEM {
    item.config()
    this.permissions.add(item)
    return item
}